package com.magic.gre.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.magic.gre.GREApp;
import com.magic.gre.R;
import com.magic.gre.adapter.MeanAdapter;
import com.magic.gre.base.activity.BaseMVPActivity;
import com.magic.gre.entity.MeanBean;
import com.magic.gre.entity.WordsDetailsBean;
import com.magic.gre.helper.Apphelper;
import com.magic.gre.mvp.contract.WordsDetailsContract2;
import com.magic.gre.mvp.presenter.WordsDetailsPresenterImpl2;
import com.magic.gre.recording.AudioPlayManager;
import com.magic.gre.recording.IAudioPlayListener;
import com.magic.gre.utils.PermissonUtils;
import com.noname.lib_base_java.util.L;
import com.noname.lib_base_java.util.ToastUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

/**
 * Author: Lmoumou
 * Date: 2019-01-28 10:05
 * 文件名: WordsDetailsActivity2
 * 描述:
 */
public class WordsDetailsActivity2 extends BaseMVPActivity<WordsDetailsPresenterImpl2> implements WordsDetailsContract2.View {

    private static final String TAG = "WordsDetailsActivity2";

    @BindView(R.id.words_tv)
    TextView wordsTv;
    @BindView(R.id.pronunciation_tv)
    TextView pronunciationTv;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;

    public static void startThis(Context context, String id) {
        Intent intent = new Intent(context.getApplicationContext(), WordsDetailsActivity2.class);
        intent.putExtra("id", id);
        context.startActivity(intent);
    }

    private String id;
    private List<MeanBean> dataList = new ArrayList<>();
    private MeanAdapter adapter;
    private RxPermissions rxPermissions;
    private Handler handler = new Handler();
    private AnimationDrawable animation;
    private WordsDetailsBean detailsBean;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_words_de;
    }

    @Override
    protected WordsDetailsPresenterImpl2 creatPresenter() {
        return new WordsDetailsPresenterImpl2(this);
    }


    @Override
    protected void netOverride() {
        mPresenter.pWordsDetails(id);
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        id = getIntent().getStringExtra("id");


        Drawable[] compoundDrawables = pronunciationTv.getCompoundDrawables();
        animation = (AnimationDrawable) compoundDrawables[2];
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new MeanAdapter(this, dataList);
        mRecyclerView.setAdapter(adapter);
        mPresenter.pWordsDetails(id);
    }

    @OnClick(value = {R.id.pronunciation_tv})
    protected void onClick(View view) {
        switch (view.getId()) {
            case R.id.pronunciation_tv:
                String dirPath = Environment.getExternalStorageDirectory() + File.separator + GREApp.getContext().getPackageName() + File.separator + "Download" + File.separator + detailsBean.getThesaurusId();
                playVoice(animation, detailsBean.getVoicePath(dirPath));
                break;
        }
    }

    @Override
    public void vWordetails(WordsDetailsBean detailsBean) {
        this.detailsBean = detailsBean;
        wordsTv.setText(detailsBean.getName());
        pronunciationTv.setText(detailsBean.getSymbol());
        dataList.clear();

        dataList.addAll(0, detailsBean.getMeanings());
        adapter.notifyDataSetChanged();

        if (Apphelper.getVoice()) {
            String dirPath = Environment.getExternalStorageDirectory() + File.separator + GREApp.getContext().getPackageName() + File.separator + "Download" + File.separator + detailsBean.getThesaurusId();
            playVoice(animation, detailsBean.getVoicePath(dirPath));
        }

    }

    /**
     * 延迟0.5秒播放音频
     *
     * @param animation
     * @param voicePath
     */
    @SuppressLint("CheckResult")
    private void playVoice(final AnimationDrawable animation, final String voicePath) {
        File file = new File(voicePath);
        if (!file.exists()) {
//            ToastUtil.getInstance().showNormal(this, "资源不存在");
            return;
        }
        if (rxPermissions == null) {
            rxPermissions = new RxPermissions(this);
        }
        rxPermissions.request(PermissonUtils.VOICE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    if (voicePath == null) {
                                        return;
                                    }
//                                    L.e("WordsDetailsActivity", "voicePath->" + voicePath);
                                    AudioPlayManager.getInstance().stopPlay();
                                    Uri audioUri = Uri.parse(voicePath);
                                    AudioPlayManager.getInstance().startPlay(WordsDetailsActivity2.this, audioUri, new IAudioPlayListener() {
                                        @Override
                                        public void onStart(Uri var1) {
                                            if (animation != null)
                                                animation.start();
                                            mRecyclerView.setNestedScrollingEnabled(false);
                                        }

                                        @Override
                                        public void onStop(Uri var1) {
                                            if (animation != null) {
                                                animation.stop();
                                                animation.selectDrawable(0);
                                                mRecyclerView.setNestedScrollingEnabled(true);
                                            }

                                        }

                                        @Override
                                        public void onComplete(Uri var1) {
                                            if (animation != null) {
                                                animation.stop();
                                                animation.selectDrawable(0);
                                                mRecyclerView.setNestedScrollingEnabled(true);
                                            }
                                        }
                                    });
                                }
                            }, 500);

                        }
                    }
                });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
